﻿namespace Kazkommertsbank.Framework.Common
{
    public static class StringExtensions
    {
        public static byte ToByte(this string str, byte defaultValue = 0)
        {
            byte value;
            return !byte.TryParse(str, out value) ? defaultValue : value;
        }

        public static short ToShort(this string str, short defaultValue = 0)
        {
            short value;
            return !short.TryParse(str, out value) ? defaultValue : value;
        }

        public static int ToInt(this string str, int defaultValue = 0)
        {
            int value;
            return !int.TryParse(str, out value) ? defaultValue : value;
        }

        public static long ToLong(this string str, long defaultValue = 0)
        {
            long value;
            return !long.TryParse(str, out value) ? defaultValue : value;
        }

        public static ushort ToUShort(this string str, ushort defaultValue = 0)
        {
            ushort value;
            return !ushort.TryParse(str, out value) ? defaultValue : value;
        }

        public static uint ToUInt(this string str, uint defaultValue = 0)
        {
            uint value;
            return !uint.TryParse(str, out value) ? defaultValue : value;
        }

        public static ulong ToULong(this string str, ulong defaultValue = 0)
        {
            ulong value;
            return !ulong.TryParse(str, out value) ? defaultValue : value;
        }

        public static float ToFloat(this string str, float defaultValue = 0f)
        {
            float value;
            return !float.TryParse(str, out value) ? defaultValue : value;
        }

        public static double ToDouble(this string str, double defaultValue = 0.0)
        {
            double value;
            return !double.TryParse(str, out value) ? defaultValue : value;
        }

        public static decimal ToDecimal(this string str, decimal defaultValue = 0)
        {
            decimal value;
            return !decimal.TryParse(str, out value) ? defaultValue : value;
        }

        public static bool ToBool(this string str, bool defaultValue = false)
        {
            bool value;
            if(bool.TryParse(str, out value))
                return value;
            if(!string.IsNullOrEmpty(str))
            {
                string strValue = str.Trim().ToLower();
                if(strValue == "false" || strValue == "0")
                    return false;
                if(strValue == "true" || strValue == "1")
                    return true;
            }

            return defaultValue;
        }
    }
}